package com.ptmall.app.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;

import com.ptmall.app.R;
import com.ptmall.app.base.BaseMvpActivity;
import com.ptmall.app.base.PermissionListener;
import com.ptmall.app.bean.LocalFile;
import com.ptmall.app.bean.LocalImageHelper;
import com.ptmall.app.net.HttpMethods;
import com.ptmall.app.net.api.ApiDataRepository;
import com.ptmall.app.net.base.ApiNetResponse;
import com.ptmall.app.net.okhttp.BusinessResponse;
import com.ptmall.app.net.okhttp.OkHttps;
import com.ptmall.app.ui.adapter.SelectImgAdapter;
import com.ptmall.app.utils.FileUtils;
import com.ptmall.app.view.GetPhotoPop;
import com.ptmall.app.view.NoScrollGridView;
import com.ptmall.app.view.TitleBarView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ShopApplyActivity extends BaseMvpActivity implements BusinessResponse {

    TitleBarView titlebar;

    Button enter;
    EditText shopwx,shopphone,shoptruename,shopcate,shopname;

    NoScrollGridView img_gv,img_gv2;

    private List<LocalFile> checkedItems = new ArrayList<>();
    private String[] VIDEO_PERMISSION = {
            Manifest.permission.CAMERA,
            //Manifest.permission.RECORD_AUDIO,
            //Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private PopupWindow mPicPopWin;
    private SelectImgAdapter mImgAdapter,mImgAdapter2;
    public static final int TAKE_CAMERA = 0x000001;
    private final int TAKE_PICTURES = 0x000002;
    private GetPhotoPop photo;
    private final int MAX_IMG_COUNT = 2;
    ApiDataRepository apiDataRepository = ApiDataRepository.getInstance();

    private List<LocalFile> checkedItems2 = new ArrayList<>();
    public static final int TAKE_CAMERA2 = 0x000003;
    private final int TAKE_PICTURES2 = 0x000004;
    private OkHttps okHttps;
    int postsize,postsize2,addsize;

    String image_path1,image_path2;
    StringBuffer stringBuffer = new StringBuffer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.activity_authshop);
    }

    @Override
    public void initViews() {
        img_gv = (NoScrollGridView) findViewById(R.id.img_gv);
        img_gv2 = (NoScrollGridView) findViewById(R.id.img_gv2);
        titlebar = (TitleBarView) findViewById(R.id.titlebar);
        enter = (Button) findViewById(R.id.enter);

        shopwx = (EditText) findViewById(R.id.shopwx);
        shopphone = (EditText) findViewById(R.id.shopphone);
        shoptruename = (EditText) findViewById(R.id.shoptruename);
        shopcate = (EditText) findViewById(R.id.shopcate);
        shopname = (EditText) findViewById(R.id.shopname);

        titlebar.setOnTitleBarClickListener(new TitleBarView.TitleBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {

            }
        });
        enter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(TextUtils.isEmpty(shopcate.getText().toString())&&
                        TextUtils.isEmpty(shopname.getText().toString())&&
                        TextUtils.isEmpty(shoptruename.getText().toString())&&
                        TextUtils.isEmpty(shopphone.getText().toString())){
                    showMsg("请填写全部信息");
                    return;
                }
                if(checkedItems.size()<2||checkedItems2.size() == 0){
                    showMsg("图片信息不全");
                    return;
                }

                for (LocalFile mLocalFile:checkedItems){
                    okHttps.postAsynFile(HttpMethods.BASE_URL+"User/uploadImage",
                            new File(mLocalFile.getOriginalUri()), true, 1);
                    postsize = 0;
                }

                addsize = checkedItems2.size();
                for (LocalFile mLocalFile:checkedItems2){
                    okHttps.postAsynFile(HttpMethods.BASE_URL+"User/uploadImage",
                            new File(mLocalFile.getOriginalUri()), true, 2);
                    postsize2 = 0;
                }
            }
        });

    }

    @Override
    public void initEvents() {

        okHttps = new OkHttps(this);
        okHttps.addResponseListener(this);

        mImgAdapter = new SelectImgAdapter(this, position -> {//删除回调
            checkedItems.remove(position);
            mImgAdapter.notifyDataSetChanged();
        }, v -> {//添加回调
            requestRuntimePermisssions(VIDEO_PERMISSION, new PermissionListener() {
                @Override
                public void onGranted() {
                    showPicDialog();
                }

                @Override
                public void onDenied(List<String> deniedList) {
                }
            });
        }, MAX_IMG_COUNT, checkedItems);
        img_gv.setAdapter(mImgAdapter);


        mImgAdapter2 = new SelectImgAdapter(this, position -> {//删除回调
            checkedItems2.remove(position);
            mImgAdapter2.notifyDataSetChanged();
        }, v -> {//添加回调
            requestRuntimePermisssions(VIDEO_PERMISSION, new PermissionListener() {
                @Override
                public void onGranted() {
                    showPicDialog2();
                }

                @Override
                public void onDenied(List<String> deniedList) {
                }
            });
        }, 9, checkedItems2);
        img_gv2.setAdapter(mImgAdapter2);


    }

    private void apply(){
        Map<String,String> map = new HashMap<>();
        map.put("trueName",shoptruename.getText().toString());
        map.put("tel",shopphone.getText().toString());
        map.put("company_name",shopname.getText().toString());
        map.put("account",shopwx.getText().toString());
        map.put("yewu",shopcate.getText().toString());
        map.put("image_path1",image_path1);
        map.put("image_path2",image_path2);
        map.put("baojia",stringBuffer.deleteCharAt(stringBuffer.length()-1).toString());
        apiDataRepository.applyshop(map, new ApiNetResponse<Object>() {
            @Override
            public void onSuccess(Object data) {
                showMsg("提交成功，等待审核");
                finish();
            }
        });
    }

    @Override
    public void OnMessageResponse(int id, String jo) {
        switch (id){
            case 1:

                try {
                    JSONObject jsonObject = new JSONObject(jo);
                    postsize++;
                    if(postsize==1){
                        image_path1 =jsonObject.getString("image_path");
                    }else if(postsize == 2){
                        image_path2 =jsonObject.getString("image_path");
                    }
                    if(postsize == 2&&postsize2 == addsize){
                        apply();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    showMsg("图片上传失败");
                }


                break;
            case 2:

                try {
                    JSONObject jsonObject = new JSONObject(jo);
                    postsize2++;
                    stringBuffer.append(jsonObject.getString("image_path")+",");
                    if(postsize == 2&&postsize2 == addsize){
                        apply();

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    showMsg("图片上传失败");
                }
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_CAMERA:
                if (resultCode != RESULT_OK) {
                    return;
                }
                if (checkedItems.size() < MAX_IMG_COUNT) {
                    String fileName = String.valueOf(System.currentTimeMillis());
                    Bitmap bm = (Bitmap) data.getExtras().get("data");
                    FileUtils.saveBitmap(bm, fileName);
                    LocalFile takePhoto = new LocalFile();
                    takePhoto.setBitmap(bm);
                    takePhoto.setOriginalUri(FileUtils.SDPATH + fileName + ".JPEG");
                    takePhoto.setIshttp(false);
                    long size = new File(takePhoto.getOriginalUri()).length();//单位是Byte(1Byte=8bit)
                    takePhoto.setSize(String.valueOf(size));
                    checkedItems.add(takePhoto);
                    mImgAdapter.notifyDataSetChanged();

                }
                break;
            case TAKE_PICTURES:
                checkedItems.addAll(LocalImageHelper.getInstance().getCheckedItems());
                LocalImageHelper.getInstance().getCheckedItems().clear();
                mImgAdapter.notifyDataSetChanged();
                break;
            case TAKE_CAMERA2:
                if (resultCode != RESULT_OK) {
                    return;
                }
                if (checkedItems2.size() < MAX_IMG_COUNT) {
                    String fileName = String.valueOf(System.currentTimeMillis());
                    Bitmap bm = (Bitmap) data.getExtras().get("data");
                    FileUtils.saveBitmap(bm, fileName);
                    LocalFile takePhoto = new LocalFile();
                    takePhoto.setBitmap(bm);
                    takePhoto.setOriginalUri(FileUtils.SDPATH + fileName + ".JPEG");
                    takePhoto.setIshttp(false);
                    long size = new File(takePhoto.getOriginalUri()).length();//单位是Byte(1Byte=8bit)
                    takePhoto.setSize(String.valueOf(size));
                    checkedItems2.add(takePhoto);
                    mImgAdapter2.notifyDataSetChanged();
                }
                break;
            case TAKE_PICTURES2:
                checkedItems2.addAll(LocalImageHelper.getInstance().getCheckedItems());
                LocalImageHelper.getInstance().getCheckedItems().clear();
                mImgAdapter2.notifyDataSetChanged();
                break;
        }
    }

    private void showPicDialog () {
        photo = new GetPhotoPop(ShopApplyActivity.this,getWindow());
        photo.setOnClickPhoto(new GetPhotoPop.OnClickPhoto() {
            @Override
            public void OnClickGallery() {
                Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(openCameraIntent, TAKE_CAMERA);
            }
            @Override
            public void OnClickPhotoGraph() {
                Intent intent = new Intent(ShopApplyActivity.this,
                        LocalAlbumActivity.class);
                intent.putExtra("num", 1);
                startActivityForResult(intent, TAKE_PICTURES);
            }
        });
    }
    private void showPicDialog2 () {
        photo = new GetPhotoPop(ShopApplyActivity.this,getWindow());
        photo.setOnClickPhoto(new GetPhotoPop.OnClickPhoto() {
            @Override
            public void OnClickGallery() {
                Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(openCameraIntent, TAKE_CAMERA2);
            }
            @Override
            public void OnClickPhotoGraph() {
                Intent intent = new Intent(ShopApplyActivity.this,
                        LocalAlbumActivity.class);
                intent.putExtra("num", 1);
                startActivityForResult(intent, TAKE_PICTURES2);
            }
        });
    }
}
